//
//  COPresentAnimation.swift
//  COmix
//
//  Created by Ruthless on 2023/8/16.
//

import UIKit

class COPresentAnimation: NSObject {

}

extension COPresentAnimation: UIViewControllerAnimatedTransitioning {
    
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        0.3
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let containerView = transitionContext.containerView
        let duration = self.transitionDuration(using: transitionContext)
        let translation = containerView.bounds.height
        if let tovc = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to), let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) {
            if tovc.isBeingPresented {
                presentedView(toView, containerView: containerView)
                toView.transform  = CGAffineTransform.identity.translatedBy(x: 0, y: translation)

                UIView.animate(withDuration: duration, delay: 0, options: UIView.AnimationOptions.curveEaseInOut) {
                    toView.transform = CGAffineTransform.identity
                } completion: { _ in
                    transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
                }

            }
        }
        if let fromVc = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from), let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from) {
            if fromVc.isBeingDismissed {
                UIView.animate(withDuration: duration, delay: 0, options: UIView.AnimationOptions.curveEaseInOut) {
                    fromView.transform = CGAffineTransform.identity.translatedBy(x: 0, y: translation)
                } completion: { _ in
                    fromView.transform = CGAffineTransform.identity
                    transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
                }
            }
        }
    }
    
    func presentedView(_ presentedView: UIView, containerView: UIView) {
        containerView.addSubview(presentedView)
        presentedView.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
        }
        
        presentedView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
        }
    }
}
